package com.its.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.its.commons.redisDao.RedisDao;
import com.its.goods.pojo.Goods;
import com.its.mapper.CartMapper;
import com.its.member.mapper.MemberMapper;
import com.its.member.pojo.Member;
import com.its.pojo.Cart;
import com.its.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【gym_cart(购物车)】的数据库操作Service实现
* @createDate 2025-05-27 15:34:29
*/
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    //依赖注入Mapper层属性
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private MemberMapper memberMapper;

    //注入Redis
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void addToCart(Goods goods, Integer mount, String memberAccount) {
        String redisKey = "cart:" + memberAccount;
        String redisJson = (String) redisTemplate.opsForValue().get(redisKey);
        List<Cart> cartList = redisJson != null ? JSON.parseArray(redisJson, Cart.class) : new ArrayList<>();

        boolean exists = false;
        for (Cart cart : cartList) {
            if (cart.getGoodsName().equals(goods.getGoodsName())) {
                cart.setMount(cart.getMount() + mount);
                cart.setSubtotal(cart.getGoodsPrice().multiply(BigDecimal.valueOf(cart.getMount())));
                cart.setMemberAccount(memberAccount);

                // 更新数据库（确保 cart.getId() 不为空）
                cartMapper.updateById(cart);
                exists = true;
                break;
            }
        }

        if (!exists) {
            Cart newItem = new Cart();
            newItem.setGid(goods.getGid());
            newItem.setGoodsName(goods.getGoodsName());
            newItem.setGoodsPrice(goods.getGoodsPrice());
            newItem.setMount(mount);
            newItem.setSubtotal(newItem.getGoodsPrice().multiply(BigDecimal.valueOf(mount)));
            newItem.setMemberAccount(memberAccount);

            cartMapper.insert(newItem);
            cartList.add(newItem);
        }

        // 更新 Redis 缓存（带过期时间）
        redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(cartList), 1, TimeUnit.DAYS);
    }



    //查询我的购物车
    @Override
    public List<Cart> getCartByMemberAccount(String memberAccount) {
        String redisKey = "cart:" + memberAccount;
        String json = (String) redisTemplate.opsForValue().get(redisKey);

        List<Cart> cartList;
        if (json != null) {
            cartList = JSON.parseArray(json, Cart.class);
        } else {
            // 查询数据库，根据用户名查 userId
            cartList = cartMapper.selectList(new LambdaQueryWrapper<Cart>().eq(Cart::getMemberAccount,memberAccount));

            // 同步写入 Redis
            redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(cartList));
        }

        return cartList;
    }


    //将商品从购物车中移除
    @Override
    public void deleteToCart(Integer id,String memberAccount) {
        // 删除数据库中记录
        cartMapper.deleteById(id);

        // 从 Redis 中获取购物车
        String redisKey = "cart:" + memberAccount;
        String json = (String) redisTemplate.opsForValue().get(redisKey);
        if (json != null) {
            List<Cart> cartList = JSON.parseArray(json, Cart.class);

            // 过滤掉要删除的项
            cartList = cartList.stream()
                    .filter(cart -> !cart.getId().equals(id))
                    .collect(Collectors.toList());

            // 同步回 Redis
            redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(cartList));
        }
    }
}




